package com.btr.ivle.backgroud;

import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;

import com.btr.ivle.R;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.DataSourceAnnouncement;
import com.btr.ivle.helper.DatabaseModule;
import com.btr.ivle.helper.URLtoString;

public class GetAnnouncementTask extends AsyncTask<String, Void, Void>{
	
	private Context context;
	
	public GetAnnouncementTask(Context context){
		this.context = context;
	}

	protected Void doInBackground(String... texts) {
		String CourseCode = texts[0], CourseID = "";
		String ID, Title, Description, CreatedDate, CreatorName;
		Boolean isRead;
		
		//DatabaseAnnouncement dbAnnouncement = new DatabaseAnnouncement(this.context,IVLEToken.getUserID()+"_Announcement",null,context.getResources().getInteger(R.integer.DBVersion));
		DatabaseModule dbModule = new DatabaseModule(this.context,IVLEToken.getUserID(),null,context.getResources().getInteger(R.integer.DBVersion));
		String table = IVLEToken.getUserID(); 
		String[] columns = new  String[] {dbModule.colID};
		String selection = dbModule.colCode + "=?";
		String[] selectionArgs = new  String[] {CourseCode};
		Cursor c = dbModule.getReadableDatabase().query(table, columns, 
				selection, selectionArgs, null, null, null, null);
		if(c.getCount()==1){
			c.moveToFirst();
			CourseID = c.getString(0);
		}
		c.close();
		dbModule.getReadableDatabase().close();
		dbModule.close();
		
		DataSourceAnnouncement datasource = new DataSourceAnnouncement(context);
		datasource.open();
		
		try{
        	URL url = new URL("https://ivle.nus.edu.sg/API/Lapi.svc/Announcements?APIKey=" +
        			context.getString(R.string.IVLE_API_KEY) + "&AuthToken=" + IVLEToken.getToken() + "&CourseID="
        				+ CourseID + "&Duration=0&TitleOnly=false");
        	
        	JSONObject jObject = new JSONObject(URLtoString.get(url));
	        JSONArray resultsArrary = jObject.getJSONArray("Results");
	        
	        //table = IVLEToken.getUserID() + "_Announcement";
	        ContentValues values;
	        
	        for (int i = 0; i < resultsArrary.length(); i++) {
	        	ID = resultsArrary.getJSONObject(i).getString("ID").toString();
	        	Title = resultsArrary.getJSONObject(i).getString("Title").toString();
	        	Description = resultsArrary.getJSONObject(i).getString("Description").toString();
	        	CreatedDate = resultsArrary.getJSONObject(i).getString("CreatedDate").toString().substring(6, 19);
	        	CreatorName = resultsArrary.getJSONObject(i).getJSONObject("Creator").getString("Name").toString();
	        	isRead = resultsArrary.getJSONObject(i).getBoolean("isRead");
	        	
	        	values = new  ContentValues();
	        	values.put(datasource.AnnouncementID, ID);
	        	values.put(datasource.CourseCode, CourseCode);
	        	values.put(datasource.Title, Title);
	        	values.put(datasource.Description, Description);
	        	values.put(datasource.CreatedDate, CreatedDate);
	        	values.put(datasource.CreatorName, CreatorName);
	        	values.put(datasource.isRead, isRead);
	        	//dbAnnouncement.getReadableDatabase().replace(table, null, values);
	        	datasource.updateEntry(values);
			}
	        //dbAnnouncement.getReadableDatabase().close();
	        //dbAnnouncement.close();
  
        }catch(Exception ex){
	    }
		return null;
	}
	
    protected void onPostExecute(Void result) {
    	@SuppressWarnings("unchecked")
		AsyncTaskCompleteListener<String> l = (AsyncTaskCompleteListener<String>) context;
    	l.onAsyncTaskComplete(""); 
    }
}
